#!/bin/bash
set -e

# 参数检查
if [ $# -ne 2 ]; then
    echo "Usage: $0 <container_name> <host_interface>"
    exit 1
fi

CONTAINER_NAME="$1"
HOST_INTERFACE="$2"

# 获取容器PID
PID=$(docker inspect -f '{{.State.Pid}}' "$CONTAINER_NAME" 2>/dev/null)
if [ -z "$PID" ]; then
    echo "Error: Container '$CONTAINER_NAME' not found."
    exit 1
fi

# 设置网络命名空间路径
mkdir -p /var/run/netns
ln -sf "/proc/$PID/ns/net" "/var/run/netns/$CONTAINER_NAME"

# 检查宿主机接口是否存在
if ! ip link show "$HOST_INTERFACE" &>/dev/null; then
    echo "Error: Host interface '$HOST_INTERFACE' does not exist."
    rm -f "/var/run/netns/$CONTAINER_NAME"
    exit 1
fi

# 生成随机接口名
RANDOM_SUFFIX=$(shuf -i 100-999 -n 1)
MACVLAN_IFNAME="mvlan${RANDOM_SUFFIX}"

# 创建macvlan接口
if ! ip link add "$MACVLAN_IFNAME" link "$HOST_INTERFACE" type macvlan mode bridge; then
    echo "Error: Failed to create macvlan interface."
    rm -f "/var/run/netns/$CONTAINER_NAME"
    exit 1
fi

# 启用宿主机接口混杂模式
ip link set "$HOST_INTERFACE" promisc on

# 转移接口到容器命名空间
ip link set "$MACVLAN_IFNAME" netns "$CONTAINER_NAME"

# 启用容器内接口
ip netns exec "$CONTAINER_NAME" ip link set "$MACVLAN_IFNAME" up

# 清理网络命名空间链接
rm -f "/var/run/netns/$CONTAINER_NAME"

echo "Successfully created macvlan interface: $MACVLAN_IFNAME"
echo "Note: You need to manually configure IP address inside the container"
